package com.gzxw.mogublog.admin.annotation.OperationLogger;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.gzxw.mogublog.base.holder.AbstractRequestAwareRunnable;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.commons.entity.SysLog;
import com.gzxw.mogublog.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class SysLogHandle extends AbstractRequestAwareRunnable {

    /**
     * 参数列表
     */
    private String paramsJson;

    /**
     * 类路径
     */
    private String classPath;

    /**
     * 方法名
     */
    private String methodName;

    /**
     * 方法请求时间
     */
    private Date startTime;

    /**
     * 操作名称
     */
    private String operationName;

    /**
     * 请求IP
     */
    private String ip;

    /**
     * 请求类型
     */
    private String type;

    /**
     * 请求URL
     */
    private String requestUrl;

    private LoginUser loginUser;

    public SysLogHandle(String paramsJson, String classPath,
                        String methodName, Date startTime,
                        String operationName, String ip,
                        String type, String requestUrl,LoginUser loginUser) {
        this.paramsJson = paramsJson;
        this.classPath = classPath;
        this.methodName = methodName;
        this.startTime = startTime;
        this.operationName = operationName;
        this.ip = ip;
        this.type = type;
        this.requestUrl = requestUrl;
        this.loginUser = loginUser;
    }

    @Override
    protected void onRun() {

        SysLog sysLog = new SysLog();

        // 设置请求信息
        sysLog.setIp(ip);

        // 设置调用的类
        sysLog.setClassPath(classPath);

        // 设置调用的方法
        sysLog.setMethod(methodName);

        sysLog.setType(type);
        sysLog.setUrl(requestUrl);

        sysLog.setOperation(operationName);
        sysLog.setCreateTime(new Date());
        sysLog.setUpdateTime(new Date());

        sysLog.setUserName("admin");
        sysLog.setAdminUid("admin");
        sysLog.setParams(paramsJson);

        //设置请求时间
        Date endTime = new Date();
        // 计算请求接口花费时间
        long spendTime = DateUtil.between(startTime, endTime, DateUnit.MS);
        sysLog.setSpendTime(spendTime);

        sysLog.insert();
    }
}
